// audio播放器
import { computed } from 'vue'
import { useStore } from 'vuex'
import { PLAY_MODE } from '../../assets/js/constant'
import usePlayHistoryEffect from './use-play-history'

export default function useAudioEffect (songReady, currentTime, progressChanging, playLyric, audioRef) {
  const { savePlay } = usePlayHistoryEffect()
  const store = useStore()
  const playMode = computed(() => store.state.playMode)
  const playList = computed(() => store.state.playList)
  const playing = computed(() => store.state.playing)
  const currentIndex = computed(() => store.state.currentIndex)
  const currentSong = computed(() => store.getters.currentSong)
  // 窃听audio标签时间变化
  const ontimeupdate = (e) => {
    if (progressChanging.value) return
    currentTime.value = e.target.currentTime
  }
  // 窃听audio标签暂停事件
  const onpause = () => {
    store.commit('setPlayingState', false)
  }
  // 窃听audio音频是否准备完成
  const onReady = () => {
    if (songReady.value) return
    songReady.value = true
    playLyric()
    savePlay(currentSong.value)
  }
  // 窃听audio音频播放错误
  const onerror = () => {
    songReady.value = true
  }
  // 窃听audio音频播放结束
  const onended = () => {
    playMode.value === PLAY_MODE.loop ? loop() : next()
  }
  // 循环播放
  function loop () {
    const audioEl = audioRef.value
    audioEl.currentTime = 0
    audioEl.play()
    store.commit('setPlayingState', true)
  }
  // 上一首
  const prev = () => {
    const list = playList.value
    if (!list.length || !songReady.value) return
    if (list.length === 1) {
      loop()
      return
    }
    const index = currentIndex.value === 0 ? list.length - 1 : currentIndex.value - 1
    store.commit('setCurrentIndex', index)
  }
  // 下一首
  const next = () => {
    const list = playList.value
    if (!list.length || !songReady.value) return
    if (list.length === 1) {
      loop()
      return
    }
    const index = currentIndex.value === list.length - 1 ? 0 : currentIndex.value + 1
    store.commit('setCurrentIndex', index)
  }
  // 播放暂停切换
  const togglePlay = () => {
    if (!songReady.value) return
    store.commit('setPlayingState', !playing.value)
  }
  return {
    ontimeupdate,
    onpause,
    onerror,
    onReady,
    onended,
    prev,
    next,
    togglePlay,
    playList,
    songReady,
    audioRef
  }
}
